iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0

挑戰目標: MockNative Camp


今天來做教師的更新API,因為我沒有實際看過教師更新的畫面,所以這邊就簡單的來更新一些欄位示範,基本上其餘欄位也只是複製到payload中的patchreq object就可以了。
PatchReq.java 密碼跟信箱一樣是要用其他方式去做更新,所以這邊並不列入可更新範圍

package com.mock.nativecamp.payload.teacher;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;

@Data
@AllArgsConstructor()
public class PatchReq {
    @NonNull
    private String firstName;
    private String middleName;
    @NonNull
    private String lastName;
    @NonNull
    private String birthday;
    private String referrerEmail;
    @NonNull
    private String country;
    @NonNull
    private String nationality;
}

TeachersController.java 這邊只貼新增的code

 @PatchMapping(path = "/patch/{userId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object patchTeacher(@PathVariable("userId") String userId, @RequestBody PatchReq patchReq) {
        return teachersServer.updateTeacher(userId, patchReq);
    }

Teachers.java teacher object 新增update method

    public Teachers updateTeacher(Teachers teacher, PatchReq patchReq) {
        teacher.setFirstName(patchReq.getFirstName());
        if (patchReq.getMiddleName() != null) {
            teacher.setMiddleName(patchReq.getMiddleName());
        }
        teacher.setLastName(patchReq.getLastName());
        teacher.setBirthday(patchReq.getBirthday());
        if (teacher.getReferrerEmail() == null & patchReq.getReferrerEmail() != null) {
            teacher.setReferrerEmail(patchReq.getReferrerEmail());
        }
        teacher.setCountry(patchReq.getCountry());
        teacher.setNationality(patchReq.getNationality());
        return teacher;
    }

TeachersServer.java 這邊做了先查詢在更新,加入檢查是否有此紀錄,沒有的話回傳404並log

  public Object updateTeacher(String userId, PatchReq patchReq) {
        Teachers teacher = teachersRepository.findByUserId(userId);
        if (teacher == null) {
            log.error(String.format("Teacher not found id: %s", userId));
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        teacher.updateTeacher(teacher, patchReq);
        teachersRepository.save(teacher);
        return new ResponseEntity(HttpStatus.ACCEPTED);
    }

沒有找到紀錄
https://ithelp.ithome.com.tw/upload/images/20210928/20140358b0j0g4KcvQ.png
log 顯示,然後可以看到用了AOP攔截並log request跟response後,不用額外加code,真的很方便。
https://ithelp.ithome.com.tw/upload/images/20210928/20140358PvfPMt4lcg.png

成功更新教師資料
https://ithelp.ithome.com.tw/upload/images/20210928/201403587TjSqDt4Ko.png
查看教師資料
https://ithelp.ithome.com.tw/upload/images/20210928/20140358gVkPTsmgch.png

接下來繼續Mock也只是重複的新增model、controller、service的CRUD,前端那邊看起來要串接應該還要很久,甚至來不及串接,我會思考剩下的時間要不要轉向其他方向,像是一些全局性error handling 或者是部署更甚至是socket以及WebRTC的實作。


上一篇
[Day 12]我也好想成為時間管理大師(後端篇)
下一篇
[Day 14]現在真的履歷導向比較好嗎(後端篇)
系列文
關於我快30歲的後端工程師,想轉職成全端工程師,在前端世界中尋求機會的那件事(後端篇)18
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言